from django.http import JsonResponse
from django.core.paginator import Paginator,EmptyPage, PageNotAnInteger
import json
from common.models import address
def dispatcher(request):
    # if 'usertype' not in request.session:
    #     return JsonResponse({
    #         'ret': 302,
    #         'msg': '未登录'},
    #         status=302)
    #
    # if request.session['usertype'] != 'mgr':
    #     return JsonResponse({
    #         'ret': 302,
    #         'msg': '用户非mgr类型'},
    #         status=302)

    # 将请求参数统一放入request 的 params 属性中，方便后续处理

    # GET请求 参数在url中，同过request 对象的 GET属性获取
    if request.method == 'GET':
        request.params = request.GET
        # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
    elif request.method in ['POST','PUT','DELETE']:
        # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
        request.params = json.loads(request.body)


    # 根据不同的action分派给不同的函数进行处理
    action = request.params['action']
    if action == 'list':
        return lists(request)
    elif action == 'add':
        return add(request)
    elif action == 'modify':
        return modify(request)
    elif action == 'del':
        return delete(request)

    else:
        return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})



def lists(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # qs = user.objects.filter(is_delete=0).values()
    user_id = request.GET.get('user_id')
    list1 = address.objects.filter(is_delete=0).filter(user_id=user_id).values()
    # 将 QuerySet 对象 转化为 list 类型
    # 否则不能 被 转化为 JSON 字符串
    res = {}
    res['status'] = 1
    res['message'] = '获取成功'
    res['data'] = list(list1)
    return JsonResponse(res)

def add(request):

    info  = request.params['data']

    # 从请求消息中 获取要添加客户的信息
    # 并且插入到数据库中
    # 返回值 就是对应插入记录的对象
    record = address.objects.create(
        user_id=info['user_id'],
        address=info['address'],
        street=info['street'],
        community =info['community'],
        number =info['number']
    )


    return JsonResponse({'ret': 0, 'id':record.id})


def modify(request):
    # 从请求消息中 获取修改客户的信息
    # 找到该客户，并且进行修改操作
    # print('123')
    customerid = request.params['id']
    newdata = request.params['newdata']

    try:
        # 根据 id 从数据库中找到相应的客户记录
        customer = address.objects.get(id=customerid)
    except address.DoesNotExist:
        return {
            'ret': 1,
            'msg': f'id 为`{customerid}`的客户不存在'
        }

    if 'name' in newdata:
        customer.name = newdata['name']
    if 'gender' in newdata:
        customer.gender = newdata['gender']
    if 'phone_number' in newdata:
        customer.phone_number = newdata['phone_number']
    if 'identify_number' in newdata:
        customer.identify_number = newdata['identify_number']
    if 'identify_positive' in newdata:
        customer.identify_positive = newdata['identify_positive']
    if 'identify_reverse' in newdata:
        customer.identify_reverse = newdata['identify_reverse']
    if 'openid' in newdata:
        customer.openid = newdata['openid']
    if 'type' in newdata:
        customer.type = newdata['type']
    if 'is_delete' in newdata:
        customer.is_delete = newdata['is_delete']
    # 注意，一定要执行save才能将修改信息保存到数据库
    customer.save()

    return JsonResponse({'ret': 0, 'msg': '更新成功','customerid':request.params['id']})

def delete(request):

    customerid = request.params['id']

    try:
        # 根据 id 从数据库中找到相应的客户记录
        customer = address.objects.get(id=customerid)
    except address.DoesNotExist:
        return  {
                'ret': 1,
                'msg': f'id 为`{customerid}`的客户不存在'
        }

    # delete 方法就将该记录从数据库中删除了
    customer.delete()

    return JsonResponse({'ret': 0})